package router

import (
	"app.com/common.v1/middleware"
	"app.com/common.v1/tool"
	"app.com/rpc.v1/config"
	"app.com/rpc.v1/internal/service"
	demo "app.com/rpc.v1/rpc/proto"
	grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
	"google.golang.org/grpc"
	"google.golang.org/grpc/reflection"
	"net"
)

type gRpcConfig struct {
	Addr         string
	RegisterFunc func(server *grpc.Server)
}

func RegisterGrpc(server *service.Service) *grpc.Server {
	c := gRpcConfig{
		Addr: config.AppConf.GrpcConf.Addr,
		RegisterFunc: func(srv *grpc.Server) {
			demo.RegisterDemoServer(srv, server.DemoService)
		},
	}

	s := grpc.NewServer(
		grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(
			middleware.RpcParams(),
		)))

	reflection.Register(s)
	c.RegisterFunc(s)

	listen, err := net.Listen("tcp", c.Addr)
	if err != nil {
		tool.Error("grpc 服务监听失败！")
		return nil
	}

	go func() {
		err := s.Serve(listen)
		if err != nil {
			tool.Error("grpc 服务启动失败！")
			return
		}
	}()

	tool.Info("grpc服务启动成功，端口" + c.Addr)
	return s
}
